package com.quxue.im.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.quxue.im.common.enums.ApplyStatusEnum;
import com.quxue.im.common.enums.ApplyTypeEnum;
import com.quxue.im.common.enums.PushNoticeEnum;
import com.quxue.im.entity.ChatApply;
import com.quxue.im.exception.LogicException;
import com.quxue.im.mapper.ChatApplyMapper;
import com.quxue.im.req.apply.ApplyHandleReq;
import com.quxue.im.req.apply.ApplyReq;
import com.quxue.im.service.IChatApplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quxue.im.service.IChatFriendService;
import com.quxue.im.service.IChatMsgService;
import com.quxue.im.vo.apply.ApplyVo;
import com.quxue.im.vo.push.PushParamVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 好友申请表 服务实现类
 * </p>
 *
 * @author jinken
 * @since 2023-11-10
 */
@Slf4j
@Service
public class ChatApplyServiceImpl extends ServiceImpl<ChatApplyMapper, ChatApply> implements IChatApplyService {

    @Resource
    private IChatMsgService chatMsgService;


    @Resource
    private IChatFriendService chatFriendService;

    @Override
    public void applyFriend(ApplyReq applyReq) {

        Long toId = applyReq.getUserId();

        /**
         * 业务逻辑处理
         * 1，判断是否是自己
         * 2，好友是否存在（如：加的过程恰好用户注销了）
         * 3，判断是否是好友，不能重复添加
         * 4，是否已经申请好友
         */
        if (StpUtil.getLoginIdAsLong() == applyReq.getUserId()) {
            LogicException.logicException("自己不能添加自己!");
        }
        QueryWrapper<ChatApply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("from_id",StpUtil.getLoginIdAsLong());
        queryWrapper.eq("to_id",applyReq.getUserId());
        queryWrapper.eq("apply_status",0);
        ChatApply existsApply = this.getOne(queryWrapper);
        if(Objects.nonNull(existsApply)){
            LogicException.logicException("已经申请好友，请不要重复申请！");
        }


        ChatApply chatApply = new ChatApply();
        chatApply.setId(IdUtil.getSnowflakeNextId());
        chatApply.setApplySource(applyReq.getSource());
        chatApply.setFromId(StpUtil.getLoginIdAsLong());
        chatApply.setToId(toId);
        chatApply.setTargetId(toId);
        chatApply.setReason(applyReq.getReason());
        chatApply.setCreateTime(LocalDateTime.now());
        chatApply.setApplyType(ApplyTypeEnum.FRIEND.getCode());
        chatApply.setApplyStatus(ApplyStatusEnum.NONE.getCode());

        log.info(chatApply.toString());
        //保存申请信息
        this.save(chatApply);

        //创建发送通知的数据对象
        PushParamVo pushParamVo = new PushParamVo();
        pushParamVo.setUserId(StpUtil.getLoginIdAsLong());
        pushParamVo.setToId(toId);
        pushParamVo.setContent(applyReq.getReason());

        /**
         * 调用聊天的service层，发送好友申请通知
         */
        chatMsgService.pushNotification(pushParamVo, PushNoticeEnum.FRIEND_APPLY);

    }

    @Override
    public List<ApplyVo> selectList() {
        long userId = StpUtil.getLoginIdAsLong();
        List<ApplyVo> applyVoList = baseMapper.selectListByToId(userId);
        return applyVoList;
    }

    @Override
    public ApplyVo applyInfo(Long applyId) {

        ApplyVo applyVo = baseMapper.selectApplyInfoById(applyId);

        return applyVo;
    }

    @Transactional
    public void applyHandle(ApplyHandleReq handleReq) {

        System.out.println("handleReq = " + handleReq);

        String applyStatus = handleReq.getApplyStatus();

        //查询出当前申请id的信息
        ChatApply chatApply = this.getById(handleReq.getApplyId());
        chatApply.setId(handleReq.getApplyId());
        chatApply.setApplyStatus(applyStatus);
        this.updateById(chatApply);


        /**
         * 如果是同意，还需要添加好友(注意，此处数据库中，无论是被加的还是加好友的各自要插入一条数据2条数据)
         */
        if(ApplyStatusEnum.AGREE.getCode().equals(applyStatus)){

            chatFriendService.addFriend(chatApply);

        }
    }
}
